import {
	commonStore
} from "@/stores/common";
import permision from "@/utils/permission.js";
import moment from "moment";
// import { log } from "console";
//获取get参数
export function getParameter(param) {
	const reg = new RegExp("[&,?,&amp;]" + param + "=([^\\&]*)", "i");
	const value = reg.exec(
		decodeURIComponent(decodeURIComponent(location.search || location.hash))
	);
	return value ? value[1] : "";
}

// 小于10补0
export function zero(val) {
	if (!val) return "00";
	return val > 9 ? val : "0" + val;
}

/**
 * 提示开启
 */
export function uniShowToast(title = "提示", duration = 5) {
	/* #ifdef H5 */
	uni.showToast({
		title: title,
		duration: 2000,
		icon:'none'
	})
	/* #endif*/


	/*#ifdef APP-PLUS*/
	uni.sendNativeEvent("showToast", {
		msg: title,
		delay: duration
	});
	/* #endif*/
}

/**
 * 提示关闭
 */
export function uniHideToast() {
	uni.hideToast();
}


/**
 * 提示开启
 */
export function uniShowLoading(title = "加载中") {
	uni.sendNativeEvent("showLoading", {
		title: title
	});
}
/**
 * 提示关闭
 */
export function uniHideLoading() {
	uni.sendNativeEvent("hideLoading");
}

/**
 * 弹框提示
 */
export function uniShowModal(title = "", content = '', callback, expand = {}) {
	uni.sendNativeEvent(
		"showModal", {
			title: title,
			content: content,
			...expand
		},
		(res) => {
			if (callback) {
				callback(res)
			}
		}
	);
}
/**
 * 弹框提示
 */
export function uniShowModalTo(
	title = "提示",
	content = "",
	callback,
	options = {}
) {
	uni.showModal({
		title: title,
		content: content,
		success: function(res) {
			if (res.confirm) {
				if (callback) {
					callback(res);
				}
			}
		},
		...options,
	});
}

/**
 * 缓存存入
 */
export function uniSetStorageSync(key, value) {
	if (!key) {
		return false;
	}
	try {
		const jsonStr = JSON.stringify(value);
		uni.setStorageSync(key, value);
	} catch (e) {
		uni.setStorageSync(key, value);
	}
}

/**
 * 缓存读取
 */
export function uniGetStorageSync(key) {
	const str = uni.getStorageSync(key);
	if (str) {
		try {
			const obj = JSON.parse(str);
			return obj;
		} catch (e) {
			return str;
		}
	} else {
		return null;
	}
}

/**
 * 缓存删除
 */
export function uniRemoveStorageSync(key) {
	if (key) {
		uni.removeStorageSync(key);
		return false;
	}
	uni.clearStorage();
}

/**
 * 去重
 * @param arr
 * @param key
 * @returns
 */
export const dupArray = (arr = [], key = "") => {
	let ret = [];

	arr.forEach((item, index, self) => {
		let compare = [];

		ret.forEach((retitem, retindex, retself) => {
			compare.push(retitem[key]);
		});

		if (compare.indexOf(item[key]) === -1) {
			ret.push(item);
		}
	});

	return ret;
};

/**
 * 字符串转成16进制
 * @param {*} str
 */
export function stringToHex(value) {
	let str = value.toString(16).toString();
	return str.length == 1 ? "0" + str : str;
}

/**
 * 检查相机权限
 */

export const checkCameraPermission = async (
	callback = false,
	setPermissionCallback = false
) => {
	const platform = uni.getSystemInfoSync().osName;
	let res = null;
	if (platform == "android") {
		res = await permision.requestAndroidPermission("android.permission.CAMERA");
	} else {
		res = await permision.judgeIosPermission("camera");
		if (!res) {
			uni.chooseImage({
				count: 1, // 默认9
				sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
				sourceType: ["camera"], // 可以指定来源是相册还是相机，默认二者都有
				success(res) {
					console.log("选取或者拍照");
				},
			});
		}
	}
	if (!res || res != 1) {
		uni.showModal({
			title: "提示",
			content: "您已经关闭相机权限,去设置",
			success: function(res) {
				if (res.confirm) {
					if (setPermissionCallback) {
						setPermissionCallback();
					}
					permision.gotoAppPermissionSetting();
				} else if (res.cancel) {
					console.log("用户点击取消");
				}
			},
		});
	} else {
		if (callback) {
			callback();
		}
	}
};

/**
 * 检查相册权限
 */

export const checkPhotoPermission = async (
	callback = false,
	setPermissionCallback = false
) => {
	const platform = uni.getSystemInfoSync().osName;
	let res = null;
	if (platform == "android") {
		res = await permision.requestAndroidPermission(
			"android.permission.READ_EXTERNAL_STORAGE"
		);
	} else {
		res = await permision.judgeIosPermission("photoLibrary");
		if (!res) {
			uni.chooseImage({
				count: 1, // 默认9
				sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
				sourceType: ["album"], // 可以指定来源是相册还是相机，默认二者都有
				success(res) {
					console.log("选取或者拍照");
				},
			});
		}
	}
	if (!res || res != 1) {
		uni.showModal({
			title: "提示",
			content: "您已经关闭相册权限,去设置",
			success: function(res) {
				if (res.confirm) {
					if (setPermissionCallback) {
						setPermissionCallback();
					}
					permision.gotoAppPermissionSetting();
				} else if (res.cancel) {
					console.log("用户点击取消");
				}
			},
		});
	} else {
		if (callback) {
			callback();
		}
	}
};

/**
 * AES 加密
 * @param {*} word
 * @param {*} keyStr
 * @returns
 */
export function encryptAES(code) {
	let key = commonStore().aesKey;
	//秘钥处理
	let c = t.enc.int8array.parse(hexBuffer(key));
	//数据处理
	let r = t.enc.int8array.parse(hexBuffer(code));
	//加密数据,出来是一个数组形式
	let n = t.enc.int8array.stringify(
		t.AES.encrypt(r, c, {
			iv: [],
			mode: t.mode.ECB,
			padding: t.pad.NoPadding,
		}).ciphertext
	);
	// //将数组转化为16进制的字符串形式
	return ab2hex(n);
}

//AES 解密
export function aesDecrypt(code) {
	let key = commonStore().aesKey;
	//秘钥处理
	var c = t.enc.int8array.parse(hexBuffer(key));
	//数据处理
	var r = t.enc.int8array.parse(hexBuffer(code)).toString(t.enc.Base64);
	//解密数据,出来是一个数组形式
	var n = t.enc.int8array.stringify(
		t.AES.decrypt(r, c, {
			iv: [],
			mode: t.mode.ECB,
			padding: t.pad.NoPadding,
		})
	);
	//将数组转化为16进制的字符串形式
	return ab2hex(n);
}

//数据封装
export function hexBuffer(str) {
	//字符串不存在，返回一个数组长度为16的0
	if (!str)
		return [...Array(16)].map((_, i) => {
			return 0;
		});
	//将字符串每两个为一组都转化为10进制的数据，数组长度为16，不够的填0
	return [...Array(16)].map((_, i) => {
		return parseInt(str.substr(2 * i, 2), 16) || 0;
	});
}

/**
 * 将数组转化为16进制的字符串形式
 * @param {*} buffer
 * @returns
 */
export function ab2hex(buffer) {
	let str = "";
	buffer.forEach((item) => {
		//判断数据是否小于0，小于0加256
		item = item >= 0 ? item : item + 256;
		//补全，两个为一组
		if (item < 16) {
			str += "0" + item.toString(16);
		} else {
			str += item.toString(16);
		}
	});

	return str;
}

/**
 * 生成两位随机数
 * @param {*} n
 * @returns
 */
export function radMixed(n = 2) {
	var chars = [
		"0",
		"1",
		"2",
		"3",
		"4",
		"5",
		"6",
		"7",
		"8",
		"9",
		"a",
		"b",
		"c",
		"d",
		"e",
		"f",
	];
	var a = "";
	for (var i = 0; i < n; i++) {
		a += chars[Math.ceil(Math.random() * 15)];
	}
	return a;
}

/**
 * @desc 函数防抖
 * @param func 函数
 * @param wait 延迟执行毫秒数
 * @param immediate true 表立即执行，false 表非立即执行
 */
export function debounce(func, wait, immediate = true) {
	let timeout;
	return function() {
		if (timeout) clearTimeout(timeout);
		if (immediate) {
			var callNow = !timeout;
			timeout = setTimeout(() => {
				timeout = null;
			}, wait);
			if (callNow) func.apply(this, arguments);
		} else {
			timeout = setTimeout(function() {
				func.apply(context, args);
			}, wait);
		}
	};
}

/**
 * 判断数据类型
 * @param data：需要判断的元素
 * @returns {blealen}
 */
export function getType(data) {
	if (typeof data !== "object" && typeof data !== "function") {
		return typeof data;
	}
	if (data === null) {
		return "null";
	}
	return toString.call(data).slice(8, -1);
}

/**
 * 对日期进行格式化，
 * @param date 要格式化的日期
 * @param format 进行格式化的模式字符串 dateFormat(yyyy-MM-dd hh:mm:ss)
 * @return String
 */
export function dateFormat(date, fmt = "YYYY-MM-DD HH:mm:ss") {
	if (!date) {
		return "";
	}
	if (typeof date === "string") {
		date = new Date(date.replace(/-/g, "/"));
	}
	if (typeof date === "number") {
		date = new Date(date);
	}
	const o = {
		"M+": date.getMonth() + 1,
		"d+": date.getDate(),
		"D+": date.getDate(),
		"h+": date.getHours() % 12 === 0 ? 12 : date.getHours() % 12,
		"H+": date.getHours(),
		"m+": date.getMinutes(),
		"s+": date.getSeconds(),
		"q+": Math.floor((date.getMonth() + 3) / 3),
		S: date.getMilliseconds(),
	};
	const week = {
		0: "\u65e5",
		1: "\u4e00",
		2: "\u4e8c",
		3: "\u4e09",
		4: "\u56db",
		5: "\u4e94",
		6: "\u516d",
	};
	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(
			RegExp.$1,
			(date.getFullYear() + "").substr(4 - RegExp.$1.length)
		);
	}
	if (/(Y+)/.test(fmt)) {
		fmt = fmt.replace(
			RegExp.$1,
			(date.getFullYear() + "").substr(4 - RegExp.$1.length)
		);
	}
	if (/(E+)/.test(fmt)) {
		fmt = fmt.replace(
			RegExp.$1,
			(RegExp.$1.length > 1 ?
				RegExp.$1.length > 2 ?
				"\u661f\u671f" :
				"\u5468" :
				"") + week[date.getDay() + ""]
		);
	}
	for (const k in o) {
		if (new RegExp("(" + k + ")").test(fmt)) {
			fmt = fmt.replace(
				RegExp.$1,
				RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
			);
		}
	}
	return fmt;
}

/**
 * 判断是否为空
 * @param v：需要判断的数据
 * @returns {boolean}
 */
export function isEmpty(v) {
	switch (typeof v) {
		case "undefined":
			return true;
		case "string":
			if (
				v.replace(/(^[ \t\n\r]*)|([ \t\n\r]*$)/g, "").length === 0 ||
				v == "null"
			)
				return true;
			break;
		case "boolean":
			if (!v) return true;
			break;
		case "number":
			if (v === 0 || isNaN(v)) return true;
			break;
		case "object":
			if (v === null || v.length === 0) return true;
			for (var i in v) {
				return false;
			}
			return true;
	}
	return false;
}

// 乘
export function mul(a = "", b = "") {
	if (!a) return "";
	let c = 0,
		d = a.toString(),
		e = b.toString();
	try {
		c += d.split(".")[1].length;
		c += e.split(".")[1].length;
	} catch (f) {}
	return (
		(Number(d.replace(".", "")) * Number(e.replace(".", ""))) / Math.pow(10, c)
	);
}

/**
 * 千分符
 * @param n {Number} 要格式的数字
 * @param cent {Number} 保留小数位
 * @param y {Boolean} 是否对值进行四舍五入
 * @returns {string|*}
 */
export function qff(n, cent = 8, y = false) {
	let num = Number(n);
	// 如果是整数,不取小数位
	if (Number.isInteger(num)) {
		cent = 0;
	}
	num = num.toString().replace(/\$|\,/g, "");
	if (isNaN(num)) {
		num = 0;
	}
	let sign = num * 1 === (num = Math.abs(num));
	num = Math.floor(num * Math.pow(10, cent) + (y ? 0 : 0.50000000001));
	let cents = num % Math.pow(10, cent);
	num = Math.floor(num / Math.pow(10, cent)).toString();
	cents = cents.toString();
	// 补足小数位到指定的位数
	while (cents.length < cent) {
		cents = "0" + cents;
	}
	// 对整数部分进行千分位格式化.
	for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
		num =
			num.substring(0, num.length - (4 * i + 3)) +
			"," +
			num.substring(num.length - (4 * i + 3));
	}
	if (cent > 0) {
		return (sign ? "" : "-") + num + "." + cents;
	} else {
		return (sign ? "" : "-") + num;
	}
}

/**
 *  手机号加*号
 * @param {String | Number} val 手机号
 */
export function phoneEncrypt(val) {
	return val.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
}

/**
 * 深拷贝
 * @param data
 */
export function deepcClone(data) {
	// 如果是值类型，直接返回结果
	if (typeof data !== "object" || data == null) {
		return data;
	}

	var res;
	if (data instanceof Array) {
		res = [];
	} else {
		res = {};
	}

	for (let key in data) {
		if (data.hasOwnProperty(key)) {
			res[key] = deepcClone(data[key]);
		}
	}
	return res;
}

// 判断字符串是否为JSON格式
export const isJSON = (str) => {
	if (typeof str == "string") {
		try {
			var obj = JSON.parse(str);
			if (typeof obj == "object" && obj) {
				return true;
			}
			return false;
		} catch (e) {
			return false;
		}
	}
};
// 获取登录信息
export const getUserInfo = (callback) => {
	const user = uniGetStorageSync("user") || {};
	//  uni.showModal({
	//       title: '002',
	//       content: JSON.stringify(user),

	//     });
	if (user.token) {
		if (callback) {
			callback();
		}
		return false;
	}
	if (uni.sendNativeEvent) {
		uni.sendNativeEvent("getUserInfo", {}, (res) => {
			if (res.code == 100 || res.code == 1) {
				uniSetStorageSync("user", res.data.userInfo);
			}
			if (callback) {
				callback();
			}

		});
	}
};
// 关闭小程序
export const closeMe = () => {
	uni.sendNativeEvent("closeMe", {
		delay: 10
	});
};
// 拉取原生界面  可选值为payPassword（修改支付密码）,cancelAccount（注销账号）,verified（实名认证）
export const showNativePage = (val) => {
	uni.sendNativeEvent("showNativePage", {
		type: val
	});
};
// 跳原生的某个界面
export const goLoginOut = (val) => {
	uni.sendNativeEvent("goLoginOut", {
		path: val
	});
};

// MP3文件处理
export function pathToBase64(path) {
	return new Promise(function(resolve, reject) {
		// app
		if (typeof plus === 'object') {
			plus.io.resolveLocalFileSystemURL(path, function(entry) {
				entry.file(function(file) {
					var fileReader = new plus.io.FileReader()
					fileReader.onload = function(evt) {
						resolve(evt.target.result)
					}
					fileReader.onerror = function(error) {
						reject(error)
					}
					fileReader.readAsDataURL(file)
				}, function(error) {
					reject(error)
				})
			}, function(error) {
				reject(error)
			})

			return
		}
	})
}

// 处理学情二期作业日期数据
export function changeDateValue(value) {
	value.forEach((item) => {
		let time = item.date_time || item.created_at;
		if (time.includes("-")) {
			item.new_date_time = moment(time).format("M.DD");
		}
	});
	// 相同日期加序号
	value.forEach((item, index) => {
		if (!item.new_date_time.includes("(")) {
			value.forEach((sub, subIndex) => {
				if (
					((item.new_date_time.includes("(") &&
							item.new_date_time.slice(0, item.new_date_time.indexOf("(")) ==
							sub.new_date_time) ||
						(!item.new_date_time.includes("(") &&
							item.new_date_time == sub.new_date_time)) &&
					index != subIndex
				) {
					if (!item.new_date_time.includes("(")) {
						item.new_date_time = `${item.new_date_time}(1`;
					}
					sub.new_date_time = `${sub.new_date_time}(${1 + (subIndex - index)
            }`;
				}
			});
		}
	});
	// console.log(value, "处理学情二期作业日期数据2");
	return value
}
// 学情时间转换
export const getStudyTime = (time) => {
	const dateObject = moment(time);
	const formatDate = dateObject.format("MM.DD");
	return formatDate;
	// console.log(formatDate, "formatDate");
};